package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"

	"github.com/example/video_backend/internal/service"
	"github.com/example/video_backend/pkg/logger"
	"go.uber.org/zap"
)

// ProxyVideoController 代理视频控制器
type ProxyVideoController struct {
	proxyVideoService service.ProxyVideoService
}

// NewProxyVideoController 创建代理视频控制器实例
func NewProxyVideoController(proxyVideoService service.ProxyVideoService) *ProxyVideoController {
	return &ProxyVideoController{
		proxyVideoService: proxyVideoService,
	}
}

// DownloadVideoByProxyRequest 下载视频请求参数
type DownloadVideoByProxyRequest struct {
	VideoURL     string `json:"video_url" binding:"required,url"`
	Title        string `json:"title" binding:"required,min=1,max=100"`
	Description  string `json:"description" binding:"max=1000"`
	CategoryID   uint   `json:"category_id" binding:"required,gt=0"`
}

// DownloadVideoByProxy 通过代理下载视频
// @Summary 通过代理下载视频
// @Description 通过代理链接下载视频并上传到系统
// @Tags 视频
// @Accept json
// @Produce json
// @Security Bearer
// @Param request body DownloadVideoByProxyRequest true "下载视频请求参数"
// @Success 200 {object} Response{data=model.Video}
// @Router /api/v1/videos/proxy-download [post]
func (c *ProxyVideoController) DownloadVideoByProxy(ctx *gin.Context) {
	// 从上下文中获取用户ID
	uid, exists := ctx.Get("userID")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "未授权"})
		return
	}

	userID, ok := uid.(uint)
	if !ok {
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: "用户ID格式错误"})
		return
	}

	// 绑定请求参数
	var req DownloadVideoByProxyRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: err.Error()})
		return
	}

	logger.Info("收到通过代理下载视频请求", 
		zap.Uint("userID", userID),
		zap.String("videoURL", req.VideoURL),
		zap.String("title", req.Title),
	)

	// 调用服务层处理下载逻辑
	video, err := c.proxyVideoService.DownloadVideoByProxy(ctx, userID, req.VideoURL, req.Title, req.Description, req.CategoryID)
	if err != nil {
		logger.Error("通过代理下载视频失败: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	// 返回成功响应
	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "视频下载成功", Data: video})
}